#include "stdafx.h"

#include "InputManager.h"
#include "camera/Camera.h"
#include "terrain/Terrain.h"


InputManager* InputManager::instance = nullptr;

InputManager* InputManager::getInstance() {
	if (!instance)
		instance = new InputManager();
	return instance;
}

#define IS_KEY_PRESSED(Key, buf, action)    \
if ( glfwGetKey(Key) )                      \
{                                           \
    keyPrevList[Key] = 1;                   \
}                                           \
else if(keyPrevList[Key])                   \
{                                           \
    action;                                 \
    keyPrevList[Key] = 0;                   \
}                                           \

#define IS_KEY_DOWN(Key, buf, action)       \
if ( glfwGetKey(Key) )                      \
    action;                                 \

InputManager::InputManager() : keyboardState(KEYS_LEN), mouseButtonState(MOUSE_LEN)
{

}
InputManager::~InputManager(){}

void InputManager::update() 
{
	for (unsigned int i = 0; i < keyboardState.size(); ++i) {
		keyboardState[i] = glfwGetKey(Game::window, key_ind[i]);
	}

	for (unsigned int i = 0; i < mouseButtonState.size(); ++i) {
		mouseButtonState[i] = glfwGetMouseButton(Game::window, mouse_ind[i]);
	}

	glfwGetCursorPos(Game::window, &mousePosState[0], &mousePosState[1]);
}

bool InputManager::isKeyClicked(Key key)
{
    assert(key < KEYS_LEN);

    if ( keyboardState[key] )  
    {
        keyPrevList[key] = 1;    
    }
    else if(keyPrevList[key])
    {   
        keyPrevList[key] = 0;    
        return true;
    } 
    return false;
}

bool InputManager::isKeyPressed(Key key)
{
    return keyboardState[key] == 1;
}

bool InputManager::isMouseClicked(MouseButton mouseButton)
{
	assert(mouseButton <= 8);

	if (mouseButtonState[mouseButton]) {
		mouseButPrevList[mouseButton] = 1;
	}
	else if (mouseButPrevList[mouseButton]) {
		mouseButPrevList[mouseButton] = 0;
		return true;
	}
	return false;
}

bool InputManager::isMousePressed(MouseButton mouseButton)
{
    return mouseButtonState[mouseButton] == GLFW_PRESS;
}

glm::dvec2 InputManager::getMousePos() 
{
    return glm::dvec2(mousePosState[0], mousePosState[1]);
}

void InputManager::setMousePos(const glm::dvec2 & pos) 
{
	glfwSetCursorPos(Game::window, pos.x, pos.y);
}

